<template>
  <div id="Permitconfig_vue">
    <!-- <el-row :gutter="30">
      <el-col :span="19">
        <el-tree
          ref="permitTree"
          :data="permits"
          :show-checkbox="true"
          :default-expand-all="true"
          node-key="id"
          v-loading="isloading"
          :check-strictly="true"
        >
        </el-tree>
      </el-col>
    </el-row> -->
    <el-row>
      <el-col :span="24" data-tip="直接在根元素下使用tabs标签会导致页面卡死，需要在前面添加一个高度不可变的块级元素或用col标签包着，这是element-ui的一个bug">
        <el-tabs v-model="active" @tab-click="handleChange">
          <el-tab-pane v-for="item in roles" :label="item.ZK_ROLE" :key="item.ZK_ID" :name="item.ZK_ID" />
        </el-tabs>
        <el-tree ref="permitTree" :data="permits" :show-checkbox="true" :default-expand-all="true" node-key="id" v-loading="isloading" :check-strictly="true" @check='nodeClick' />
        <div class="btns" style="text-align:center;">
          <el-button type="primary" :disabled="isloading" style="margin-top:30px;" size="small" @click="update" icon="fa fa-save fa-lg">
            保存设置
          </el-button>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  data() {
    return {
      active: '',
      roles: [],
      rawPermitList: [],
      permits: [],
      selected: [],
      isloading: false,
    };
  },
  created() {
    this.getRoleList();
    this.getPermitTree();
  },
  methods: {
    nodeClick(node, { checkedKeys }) {
      const checked = checkedKeys.includes(node.id);
      const ids = JSON.parse(JSON.stringify(checkedKeys));
      const cids = [node.id, ...this.getNodeChildIds(node)]; // 后代元素
      if (checked) {
        ids.push(...cids); // 添加后代元素
        ids.push(...this.getParentNodeIds(node)); // 添加父级元素
      } else {
        const nids = [];
        ids.forEach(id => {
          if (!cids.includes(id)) {
            nids.push(id); // 删除后代元素(循环删除的反思路)
          }
        });
        ids.splice(0, ids.length);
        ids.push(...nids);
      }
      this.$refs.permitTree.setCheckedKeys(Array.from(new Set(ids))); // 去重设置
    },
    getNodeChildIds(node) {
      const ids = [];
      node.children.forEach(item => {
        ids.push(item.id);
        if (item.children.length > 0) {
          ids.push(...this.getNodeChildIds(item));
        }
      });
      return ids;
    },
    getParentNodeIds(node) {
      const ids = [];
      this.rawPermitList.forEach(item => {
        if (item.ZK_ID === node.pid) {
          ids.push(item.ZK_ID);
          if (item.ZK_PARENT) {
            ids.push(...this.getParentNodeIds(item));
          }
        }
      });
      return ids;
    },
    getRoleList() {
      this.$http.get('/api/permitconfig/rolelist').then(res => {
        if (res.data.flag === 'True') {
          this.roles = res.data.result;
          /* eslint-disable operator-linebreak */
          this.active =
            res.data.result.length > 0 ? res.data.result[0].ZK_ID : '';
          this.handleChange();
        }
      });
    },
    getPermitTree() {
      this.$http.get('/api/permitconfig/permitlist').then(res => {
        if (res.data.flag === 'True') {
          this.rawPermitList = JSON.parse(JSON.stringify(res.data.result));
          this._build(res.data.result);
        }
      });
    },
    _build(data) {
      this.permits = this._buildNode(null, data);
    },
    _buildNode(parent, store) {
      const obj = [];
      store.forEach(item => {
        if (!item.ZK_PARENT) {
          /* eslint-disable no-param-reassign */
          item.ZK_PARENT = null;
        }
        if (item.ZK_PARENT === parent) {
          obj.push({
            pid: item.ZK_PARENT,
            id: item.ZK_ID,
            label: item.ZK_NAME,
            children: this._buildNode(item.ZK_ID, store),
          });
        }
      });
      return obj;
    },
    handleChange() {
      this.isloading = true;
      this.$http
        .post('/api/permitconfig/permitlist', {
          ROLE: this.active,
        })
        .then(res => {
          this.isloading = false;
          this.$refs.permitTree.setCheckedKeys([]);
          if (res.data.flag === 'True') {
            this.selected = [];
            res.data.result.forEach(item => {
              this.selected.push(item.ZK_PERMITID);
            });
            this.$refs.permitTree.setCheckedKeys(this.selected);
          }
        });
    },
    update() {
      const permits = this.$refs.permitTree.getCheckedKeys().join(',');
      this.$http
        .post(
          '/api/permitconfig/update',
          { ROLE: this.active, PERMITS: permits },
          { emulateJSON: true },
        )
        .then(res => {
          if (res.data.flag === 'True') {
            this.$message.success('设置成功');
          }
        });
    },
  },
};
</script>

<style></style>
